package edu.zjut.hjg.saas.biz.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import edu.zjut.hjg.saas.biz.dao.AlbumDao;
import edu.zjut.hjg.saas.biz.model.Album;
import edu.zjut.hjg.saas.biz.support.AlbumType;
import edu.zjut.hjg.saas.biz.support.Paginated;

public class AlbumDaoImpl extends SqlMapClientDaoSupport implements AlbumDao {

    @Override
    public Integer create(Album album) {
        return (Integer) getSqlMapClientTemplate().insert("album.create", album);
    }

    @Override
    public void deleteByIdAndAppId(int id, int appId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("id", id);
        params.put("appId", appId);
        getSqlMapClientTemplate().delete("album.deleteByIdAndAppId", params);
    }

    @SuppressWarnings("unchecked")
    @Override
    public Paginated<Album> listByAlbumTypeAndAppId(AlbumType albumType, int appId, int pageSize,
                                                    int page) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("appId", appId);
        params.put("albumType", albumType);
        Integer totalSize = (Integer) getSqlMapClientTemplate().queryForObject(
                "album.countByAlbumTypeAndAppId", params);
        int start = pageSize * (page - 1);
        if (start > totalSize) {
            start = (totalSize / pageSize) * pageSize;
        }
        params.put("pageSize", pageSize);
        params.put("start", start);
        List<Album> list = getSqlMapClientTemplate().queryForList("album.listByAlbumTypeAndAppId",
                params);
        Paginated<Album> paginated = new Paginated<Album>();
        paginated.setValues(list);
        paginated.setPageSize(pageSize);
        paginated.setStart(start);
        paginated.setTotalSize(totalSize);
        return paginated;
    }

    @Override
    public Album load(int id) {
        return (Album) getSqlMapClientTemplate().queryForObject("album.load", id);
    }

    @Override
    public Album findByIdAndAppId(int id, int appId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("id", id);
        params.put("appId", appId);
        return (Album) getSqlMapClientTemplate().queryForObject("album.findByIdAndAppId", params);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Album> listAllByAlbumTypeAndAppId(AlbumType albumType, int appId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("appId", appId);
        params.put("albumType", albumType);
        return getSqlMapClientTemplate().queryForList("album.listAllByAlbumTypeAndAppId", params);
    }
}
